package xiaopiya.robot.system;

import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

import xiaopiya.robot.handler.IMessageHandler;

/**
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class NoticeMessageHandler implements IMessageHandler
{
	private final static Log LOG = LogFactory
			.getLog(NoticeMessageHandler.class);

	private String securityUser = "2330620@cdream.com";

	private IFriendService friendService;

	public void setSecurityUser(String securityUser)
	{
		this.securityUser = securityUser;
	}

	public void setFriendService(IFriendService friendService)
	{
		this.friendService = friendService;
	}

	public void handle(XMPPConnection connection, Chat chat, Message message,
			String body) throws XMPPException
	{
		String from = message.getFrom().split("/")[0];
		if (LOG.isInfoEnabled())
		{
			LOG.info("handle notice[" + body + "] from [" + from + "]");
		}

		if (this.securityUser.equals(from))
		{
			Collection<Friend> friends = this.friendService.getFriends();
			ChatManager chatManager = connection.getChatManager();
			for (Friend friend : friends)
			{
				if (friend.isBooking())
				{
					Chat friendChat = chatManager.createChat(friend
							.getFriendid(), null);
					friendChat.sendMessage(body);
					friendChat = null;
				}
			}
			chat.sendMessage("发送新闻成功！");
		} else
		{
			chat.sendMessage("您没有进行新闻发布的权限，请联系管理员");
		}
	}
}
